package someTestExcemple.tcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器启动...");
        //创建一个服务器端Socket，即ServerSocket，指定绑定的端口，并监听此端口
        //客户端服务器需要绑定同一端口
        ServerSocket serverSocket = new ServerSocket(8888);
        //等待客户端连接请求  ---阻塞式等待
        Socket socket =serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        DataInputStream dis = new DataInputStream(inputStream);

        while (true) {
            try {
                System.out.println("客户端说："+dis.readUTF());
                SocketAddress socketAddress = socket.getRemoteSocketAddress();
                System.out.println("客户端地址："+socketAddress);
            } catch (Exception e) {
                System.out.println("客户端已经断开连接");
                dis.close();
                socket.close();
                break;
            }
//            dis.close();
//            socket.close();
        }
    }
}
